// src/utils/configLoader.ts

// 完整配置类型（可根据需要扩展）
export interface AppConfig {
  logging: {
    enable: boolean;
    level: 'debug' | 'info' | 'warn' | 'error' | 'silent';
    modules: string[]; // 模块白名单，空数组表示全部
  };
  features: {
    experimental_ui: boolean;
    auto_save: boolean;
    max_history: number;
  };
  debug: {
    enable_profiling: boolean;
  };
}

// 运行时缓存解析后的配置
let cachedConfig: AppConfig | null = null;

/**
 * 从 /config/app.config 加载并解析配置
 */
export async function loadAppConfig(): Promise<AppConfig> {
  if (cachedConfig) {
    return cachedConfig;
  }

  try {

    console.log({
      message:'开始加载配置文件'
    });

    const response = await fetch('/config/app.config');
    if (!response.ok) throw new Error('Config file not found');

    const text = await response.text();
    const config = parseConfig(text);

    cachedConfig = config;
    return config;
  } catch (error) {
    console.warn('Failed to load app.config, using defaults:', error);
    // 返回默认配置（安全兜底）
    return getDefaultConfig();
  }
}

/**
 * 解析文本配置为对象
 */
function parseConfig(text: string): AppConfig {
  const config: Partial<AppConfig> = {};
  let currentGroup: string | null = null;

  text.split('\n').forEach(line => {
    const trimmed = line.trim();
    // 跳过空行和注释
    if (!trimmed || trimmed.startsWith('#')) return;

    // 匹配 [group]
    const groupMatch = trimmed.match(/^\[(\w+)\]$/);
    if (groupMatch) {
      currentGroup = groupMatch[1].toLowerCase();
      return;
    }

    // 匹配 key = value
    const kvMatch = trimmed.match(/^([^=]+)=(.*)$/);
    if (kvMatch && currentGroup) {
      const key = kvMatch[1].trim().toLowerCase();
      let value = kvMatch[2].trim();

    // 自动转换类型
    if (value.toLowerCase() === 'true') value = 'true';
    else if (value.toLowerCase() === 'false') value = 'false';
    else if (!isNaN(Number(value))) value = Number(value).toString();

    // // 初始化分组
    // if (!config[currentGroup]) {
    //   config[currentGroup] = {};
    // }

    // 类型安全赋值 - 使用类型守卫确保只处理有效的分组
    switch (currentGroup) {
      case 'logging':
        if (!config.logging) {
          config.logging = { enable: false, level: 'info', modules: [] };
        }
        if (key === 'enable') {
          config.logging.enable = value === 'true';
        } else if (key === 'level') {
          config.logging.level = ['debug', 'info', 'warn', 'error', 'silent'].includes(value)
            ? (value as 'debug' | 'info' | 'warn' | 'error' | 'silent')
            : 'info';
        } else if (key === 'modules') {
          config.logging.modules = value
            .split(',')
            .map(s => s.trim())
            .filter(Boolean);
        }
        break;

      case 'features':
        if (!config.features) {
          config.features = { experimental_ui: false, auto_save: true, max_history: 10 };
        }
        if (key === 'experimental_ui') {
          config.features.experimental_ui = value === 'true';
        } else if (key === 'auto_save') {
          config.features.auto_save = value === 'true';
        } else if (key === 'max_history') {
          config.features.max_history = parseInt(value, 10) || 10;
        }
        break;

      case 'debug':
        if (!config.debug) {
          config.debug = { enable_profiling: false };
        }
        if (key === 'enable_profiling') {
          config.debug.enable_profiling = value === 'true';
        }
        break;
      }

      console.log({
        config:config
      });
    }
  });

  return {
    logging: { enable: false, level: 'info', modules: [] },
    features: { experimental_ui: false, auto_save: true, max_history: 10 },
    debug: { enable_profiling: false },
    ...config,
  } as AppConfig;
}

/**
 * 默认配置兜底
 */
function getDefaultConfig(): AppConfig {
  return {
    logging: { enable: false, level: 'info', modules: [] },
    features: { experimental_ui: false, auto_save: true, max_history: 10 },
    debug: { enable_profiling: false },
  };
}
